package com.explorati.MaxHeap.leetcode;

import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.PriorityQueue;

public class Solution1 {
	private class Freq {
		int e, freq;

		public Freq(int e, int freq) {
			this.e = e;
			this.freq = freq;
		}

	}

	public class FreqComparator implements Comparator<Freq> {

		@Override
		public int compare(Freq a, Freq b) {
			return a.freq - b.freq;
		}
	}

	public List<Integer> topKFrequent(int[] nums, int k) {
		HashMap<Integer, Integer> map = new HashMap<>();
		for (int num : nums) {
			if (map.containsKey(num)) {
				map.put(num, map.get(num) + 1);
			} else {
				map.put(num, 1);
			}
		}

		PriorityQueue<Freq> pq = new PriorityQueue<>(new FreqComparator());
		for (int key : map.keySet()) {
			// 如果没有达到相应个数，则添加
			if (pq.size() < k)
				pq.add(new Freq(key, map.get(key)));
			else if (map.get(key) > pq.peek().freq) {
				pq.remove();
				pq.add(new Freq(key, map.get(key)));
			}
		}

		LinkedList<Integer> res = new LinkedList<>();
		while (!pq.isEmpty()) {
			res.add(pq.remove().e);
		}
		return res;
	}
}
